package site.interceptor;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import org.apache.struts2.StrutsStatics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import site.annotations.LoginVerifyAction;
import site.security.AesCryptor;
import site.util.CommonUtils;
import site.util.CookieUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginVerifyInterceptor extends MethodFilterInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginVerifyInterceptor.class);

    private static final short LOGIN_HTTP_CODE = 600;

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        LoginVerifyAction loginVerifyAction = invocation.getAction().getClass().getAnnotation(LoginVerifyAction.class);

        if (loginVerifyAction == null) {
            return invocation.invoke();
        }

        if (CommonUtils.isLoginVerifyMethod(invocation)) {
            return invocation.invoke();
        }

        ActionContext actionContext = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
        HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);

        // 解析登录cookie信息，判断是否已登录
        try {
            String loginInfo = CookieUtils.getCookieValue(request, "UT", "cookie has no user info");
            String loginName = new AesCryptor().decrypt(loginInfo);
            logger.info("登录人：{}！", loginName);
        } catch (Exception e) {
            logger.info("您还未登录，请先登录！");
            return loginProcess(request, response);
        }
        return invocation.invoke();
    }

    private String loginProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String loginUrl = "/login" + "?url=/works/list";
        if (isAjaxRequest(request)) {
            response.sendError(LOGIN_HTTP_CODE, loginUrl);
        } else {
            response.sendRedirect(loginUrl);
        }
        return Action.NONE;
    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header)) {
            return true;
        }
        return false;
    }

}
